package com.party.web.web.controller.crowdfundMultiple;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.*;
import com.party.core.model.label.Label;
import com.party.core.model.log.BehaviorType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IEventGradationService;
import com.party.core.service.crowdfund.IProjectGradationService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.distributor.IDistributorRelationService;
import com.party.core.service.label.ILabelService;
import com.party.web.biz.activity.ActivityBizService;
import com.party.web.biz.asynexport.IAsynExportService;
import com.party.web.biz.crowdfund.AnalyzeBizService;
import com.party.web.biz.crowdfund.ProjectBizService;
import com.party.web.biz.crowdfundMultiple.ProjectMultipleBizService;
import com.party.web.biz.file.ExcelExportService;
import com.party.web.utils.excel.ExportExcel;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.annotation.UserOperate;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.output.crowdfund.AnalyzeOutput;
import com.party.web.web.dto.output.crowdfund.ProjectForActivityMultiOutput;
import com.party.web.web.dto.output.crowdfund.TypeCountOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ProjectMultipleController
 * @Description 众筹控制器
 * @Author yifeng
 * @Date 2019/3/22 10:25
 **/
@Controller
@RequestMapping("activityMultiple/project")
public class ProjectMultipleController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private ProjectMultipleBizService projectMultipleBizService;
    @Autowired
    private IProjectGradationService projectGradationService;
    @Autowired
    private AnalyzeBizService analyzeBizService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ILabelService labelService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ProjectBizService projectBizService;
    @Autowired
    private IDistributorRelationService distributorRelationService;
    @Autowired
    private ICrowdfundEventService crowdfundEventService;
    @Resource(name = "projectAsynExportService")
    private IAsynExportService projectAsynExportService;
    @Autowired
    private ExcelExportService excelExportService;
    @Autowired
    private IEventGradationService eventGradationService;
    @Autowired
    private ActivityBizService activityBizService;

    /**
     * 众筹列表
     *
     * @param id      活动编号
     * @param project 众筹信息
     * @param page    分页参数
     * @return 输出视图
     */
    @DataControl
    @RequestMapping(value = "listForActivity")
    public ModelAndView listForActivity(@ControlParam(table = "activity", column = "member") String id,
                                        ProjectWithAuthor project, Page page, String currentGradation) {
        ModelAndView modelAndView = new ModelAndView("crowdfundMultiple/crowdListActivity");
        page.setLimit(20);

        modelAndView.addAllObjects(projectMultipleBizService.listForActivity(id, project, page));

        modelAndView.addObject("projectWithAuthor", project);
        modelAndView.addObject("crowdfundNum", page.getTotalCount());
        modelAndView.addAllObjects(activityBizService.putZipInfo(Constant.PRE_ZIP_URL + project.getCurrentGradation().substring(10, 15) + id));
        modelAndView.addObject("page", page);
        return modelAndView;
    }

    /**
     * 众筹列表
     *
     * @param activityId 活动编号
     * @param project    众筹信息
     * @return 输出视图
     */
    @ResponseBody
    @UserOperate(moduleName = "多场众筹项目-数据查看-众筹列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "listForActivityExport")
    public AjaxResult listForActivityExport(String activityId, ProjectWithAuthor project, HttpServletRequest request) {
        if (StringUtils.isEmpty(activityId)) {
            return AjaxResult.error("活动id不能为空");
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                projectAsynExportService.exportMultipleProject(activityId, project, request.getSession().getId());
            }
        }).start();
        return AjaxResult.success();
    }

    /**
     * @param project
     * @return
     * @Author yifeng
     * @Description 众筹主题导出
     * @Date 19:33 2019/3/28
     **/
    @ResponseBody
    @UserOperate(moduleName = "多场众筹主题-数据查看-众筹列表", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "listForEventExport")
    public AjaxResult listForEventExport(ProjectWithAuthor project) {
        if (StringUtils.isEmpty(project.getEventId())) {
            return AjaxResult.error("活动id不能为空");
        }
        try {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(project.getEventId());
            EventGradation eventGradation = eventGradationService.get(project.getCurrentGradation());
            String[] array = {"一", "二", "三", "四", "五"};
            String tt = array[eventGradation.getGradation() - 1];
            String fileName = crowdfundEvent.getName() + "的第" + tt + "场的活动.xlsx";
            List<ProjectForActivityMultiOutput> outputs = projectMultipleBizService.listForEventExport(project);
            ExportExcel exportExcel = new ExportExcel(fileName, ProjectForActivityMultiOutput.class).setDataList(outputs);
            String allPath = excelExportService.getExcelPath(fileName, "crowdfund/event", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (Exception e) {
            logger.error("主题导出异常", e);
            return AjaxResult.error("主题导出异常");
        }
    }

    /**
     * 根据分销关系查询众筹列表
     *
     * @param relationId 分销关系
     * @param page       分页参数
     * @return 众筹列表
     */
    @DataControl
    @RequestMapping(value = "activity/listForDistributor")
    public ModelAndView listForDistributorActivity(@ControlParam(table = "activity", column = "member", isDistribution = true) String relationId, Page page) {
        ModelAndView modelAndView = new ModelAndView("activity/crowdfundList");
        modelAndView.addObject("isMultiple", true);
        modelAndView.addAllObjects(projectBizService.listForDistributorCommonActivity(relationId, page));
        return modelAndView;
    }

    /**
     * 事项联合发起项目
     *
     * @param relationId 关系编号
     * @param eventId    事件编号
     * @param page       分页参数
     * @return 交互数据
     */
    @DataControl
    @RequestMapping(value = "event/listForDistributor")
    public ModelAndView listForDistributorEvent(@ControlParam(table = "zc_event", column = "create_by") String eventId,
                                                @ControlParam(table = "activity", column = "member", isDistribution = true) String relationId, Page page) {
        ModelAndView modelAndView = new ModelAndView("crowdfund/crowdfundList");
        modelAndView.addObject("isMultiple", true);
        modelAndView.addAllObjects(projectBizService.listForDistributorCommonEvent(eventId, relationId, page));
        return modelAndView;
    }

    /**
     * @param projectId 众筹id
     * @return com.party.web.web.dto.AjaxResult
     * @Author yifeng
     * @Description 获取众筹的阶段数据
     * @Date 10:31 2019/3/22
     **/
    @ResponseBody
    @RequestMapping(value = "projectGradationList")
    public ModelAndView projectGradationList(String projectId) {
        ModelAndView mv = new ModelAndView("crowdfundMultiple/projectGradationList");
        List<Map<String, Object>> projectGradations = projectGradationService.listForProjectId(projectId);
        mv.addObject("projectGradations", projectGradations);
        return mv;
    }

    /**
     * @param projectIds        众筹id
     * @param competitionStatus 状态 1：参赛 2：未参赛
     * @param eventGradationId  当前阶段id
     * @return com.party.web.web.dto.AjaxResult
     * @Author yifeng
     * @Description 设置参赛状态
     * @Date 10:15 2019/3/25
     **/
    @ResponseBody
    @RequestMapping(value = "setCompetitionStatus")
    public AjaxResult setCompetitionStatus(String projectIds, Integer competitionStatus, String eventGradationId) {
        if (StringUtils.isEmpty(projectIds)) {
            return AjaxResult.error("众筹者id不能为空");
        }
        if (StringUtils.isEmpty(eventGradationId)) {
            return AjaxResult.error("阶段id不能为空");
        }
        if (null == competitionStatus) {
            return AjaxResult.error("参与状态不能为空");
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (String projectId : projectIds.split(",")) {
                if (StringUtils.isEmpty(projectId)) {
                    continue;
                }
                ProjectGradation projectGradation = projectGradationService.getUnique(new ProjectGradation(projectId, eventGradationId));
                if (null != projectGradation && null == projectGradation.getCompetitionStatus()) {
                    if (ProjectGradation.DEFAULT_SUCCESS_TIME.equals(sdf.format(projectGradation.getSuccessTime()))) {
                        continue;
                    }
                    if (YesNoStatus.YES.getCode().equals(competitionStatus)) {
                        projectGradation.setCompetitionStatus(competitionStatus);
                        projectGradationService.update(projectGradation);
                    } else {
                        boolean result = projectMultipleBizService.transfer(projectGradation);
                        if (!result) {
                            return AjaxResult.error("设置参赛状态异常");
                        }
                    }
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("设置参赛状态异常", e);
            return AjaxResult.error("设置参赛状态异常");
        }
    }

    /**
     * @param projectAnalyze
     * @return
     * @Author yifeng
     * @Description 数据分析
     * @Date 15:25 2019/3/25
     **/
    @RequestMapping(value = "analyzeList")
    public ModelAndView analyzeList(@ControlParam(table = {"zc_event", "activity"}, column = {"create_by", "member"},
            getMethodName = {"getEventId", "getTargetId"}, isProjectId = {false, false}) ProjectAnalyze projectAnalyze) {
        ModelAndView modelAndView = new ModelAndView("crowdfundMultiple/analyzeList");
        String eventId = projectAnalyze.getEventId();
        if (StringUtils.isNotEmpty(projectAnalyze.getTargetId())) {
            Activity activity = activityService.get(projectAnalyze.getTargetId());
            eventId = activity.getEventId();
            modelAndView.addObject("activity", activity);
        }

        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);


        Map<String, Object> listCommon = projectMultipleBizService.eventGradations(eventId, projectAnalyze.getCurrentGradationId());
        projectAnalyze.setCurrentGradationId(listCommon.get("currentGradation").toString());

        List<String> dateList = null;
        List<Label> labelList = null;
        TypeCountOutput countOutput = null;
        TypeCountOutput dpCountOutput = null;
        Double totalAmount = null;


        if (projectAnalyze != null && (StringUtils.isNotBlank(projectAnalyze.getTargetId()) || StringUtils.isNotBlank(projectAnalyze.getEventId()))) {

            dateList = analyzeBizService.dateStringList();
            labelList = labelService.list(new Label());
            countOutput = analyzeBizService.countList(projectAnalyze);
            dpCountOutput = analyzeBizService.countDirectList(projectAnalyze);
            totalAmount = projectService.sumForActualAmount(projectAnalyze, 0);
        }

        modelAndView.addObject("dateList", JSONObject.toJSON(dateList));
        modelAndView.addObject("labelList", JSONObject.toJSON(labelList));
        modelAndView.addObject("count", countOutput);
        modelAndView.addObject("directCount", dpCountOutput);
        modelAndView.addObject("projectAnalyze", projectAnalyze);
        modelAndView.addObject("totalAmount", totalAmount);
        modelAndView.addObject("crowdfundEvent", crowdfundEvent);
        modelAndView.addAllObjects(listCommon);
        return modelAndView;
    }

    /**
     * 根据事件查询众筹列表
     *
     * @param projectWithAuthor 查询数据
     * @param page              分页参数
     * @return 交互数据
     */
    @DataControl
    @RequestMapping(value = "listForEvent")
    public ModelAndView listForEvent(@ControlParam(table = "zc_event", column = "create_by", getMethodName = "getEventId")
                                             ProjectWithAuthor projectWithAuthor, Page page, String currentGradation) {
        page.setLimit(20);
        ModelAndView modelAndView = new ModelAndView("crowdfundMultiple/crowdListEvent");

        // 联合发起人数
        Integer representNum = distributorRelationService.countForEvent(projectWithAuthor.getEventId());
        modelAndView.addObject("representNum", representNum);
        modelAndView.addObject("page", page);
        modelAndView.addObject("projectWithAuthor", projectWithAuthor);

        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectWithAuthor.getEventId());
        modelAndView.addObject("crowdfundEvent", crowdfundEvent);

        modelAndView.addAllObjects(projectMultipleBizService.listForEvent(projectWithAuthor, page, currentGradation));
        return modelAndView;
    }


    /**
     * 数据导出
     *
     * @param projectAnalyze 众筹分析
     * @param response       导出数据
     * @return 交互
     */
    @ResponseBody
    @UserOperate(moduleName = "多场众筹项目/主题-数据分析", behaviorType = BehaviorType.EXPORT)
    @RequestMapping(value = "analyzeListExport")
    public AjaxResult listExport(ProjectAnalyze projectAnalyze, HttpServletResponse response) {
        String[] array = {"一", "二", "三", "四", "五"};
        EventGradation eventGradation = eventGradationService.get(projectAnalyze.getCurrentGradationId());
        String tt = array[eventGradation.getGradation() - 1];
        String fileName = "数据分析.xlsx";

        if (!Strings.isNullOrEmpty(projectAnalyze.getTargetId())) {
            Activity activity = activityService.get(projectAnalyze.getTargetId());
            fileName = activity.getTitle() + "的第" + tt + "场.xlsx";
        } else if (!Strings.isNullOrEmpty(projectAnalyze.getEventId())) {
            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(projectAnalyze.getEventId());
            fileName = crowdfundEvent.getName() + "的第" + tt + "场.xlsx";
        }

        List<AnalyzeOutput> outputList = analyzeBizService.list(projectAnalyze, null);
        try {
            String allPath = analyzeBizService.export(fileName, outputList, response, YesNoStatus.YES.getCode());
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出联合发起的众筹异常", e);
        }
        return AjaxResult.error("导出异常");
    }
}